from kivy.graphics import Rectangle
from kivy.logger import Logger
from kivy.resources import resource_find
from kivy.uix.label import Label
from kivy.uix.widget import Widget

class Thumbnail(Widget):
	def __init__(self, image, text="", metadata=None, callback=None, size=(150,100), *args, **kwargs):
		super(Thumbnail, self).__init__(*args, **kwargs)
		self.image = image
		self.selected = False
		self.metadata = metadata
		self.callback = callback
		self.hidden_position = (-500, -500)
		with self.canvas:
			self.poster = Rectangle(size=size, source=image, pos=self.hidden_position, *args, **kwargs)
		self.label = None
		if text:
			self.label = Label(text=text)
			self.add_widget(self.label)
		self.bind(pos=self.change_position)

	def change_position(self, instance, position):
		self.poster.pos = position
		if self.label:
			self.label.pos = position

	def on_touch_down(self, touch):
		if touch.button == 'left' and self.collide_point(touch.pos[0], touch.pos[1]):
			self.selected = True

	def on_touch_up(self, touch):
		if touch.button == 'left' and self.collide_point(touch.pos[0], touch.pos[1]) and self.selected:
			Logger.info("Select, %s, callback=%s", self.metadata or self.image, self.callback)
			if self.callback:
				self.callback(self.metadata or self.image)
				self.selected = False
				return True
		self.selected = False
		return super(Thumbnail, self).on_touch_up(touch)

class DVDBase(Thumbnail):
	def __init__(self, image, text="", metadata=None, callback=None, size=(100,150), *args, **kwargs):
		super(DVDBase, self).__init__(image=image, text=text, metadata=metadata, callback=callback, size=size, *args, **kwargs)
		with self.canvas:
			self.box = Rectangle(size=size, source=resource_find("dvdbox.png"), pos=self.hidden_position)

	def change_position(self, instance, position):
		self.poster.pos = self.box.pos = position
		if self.label:
			self.label.pos = position

class DVDBox(DVDBase):
	def __init__(self, show, *args, **kwargs):
		super(DVDBox, self).__init__(show.detail_poster, metadata=show, *args, **kwargs)

